js
(() => {
// 默认渠道名,可以根据需要修改
const channel = 'siyuan-runjs';
// 创建socket客户端
createSocketClient(channel);
// 当收到消息时被调用
function onReceivedMessage(event) {
let request = parseJson(event.data);
let result = '';
try {
result = (new Function(request.code))();
} catch (e) {
result = e.message || '';
console.error(e);
}
if(request.fromChannel) {
postMessage(request.fromChannel, result);
}
}
// 创建socket客户端
function createSocketClient(channel) {
// 连接 WebSocket 服务器
const socket = new WebSocket('ws://'+location.host+'/ws/broadcast?channel='+channel);
socket.onopen = function(e) {
console.log('Channel '+channel+' connectioned!');
};
socket.onmessage = onReceivedMessage;
socket.onclose = function(event) {
console.log('Channel '+channel+' closed!');
};
socket.onerror = function(error) {
console.error('WebSocket Error:', error);
};
return socket;
}
// 客户端向服务器发送消息
function sendMessage(socket, message) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(message);
} else {
console.error('WebSocket connection is not open');
}
}
// 服务器向客户端发消息
async function postMessage(channel, message) {
const result = await fetchSyncPost('/api/broadcast/postMessage', {
channel: channel,
message: message
});
if(result.code !== 0 || !result.data) {
console.error('postMessage error', result);
}
}
// 解析json
function parseJson(jsonString) {
let json = {};
try {
json = JSON.parse(jsonString || '{}');
} catch(e) {
json = {};
console.error('parseJson error', e);
}
return json;
}
// 发送api请求
async function fetchSyncPost(url, data, returnType = 'json') {
const init = {
method: "POST",
};
if (data) {
if (data instanceof FormData) {
init.body = data;
} else {
init.body = JSON.stringify(data);
}
}
try {
const res = await fetch(url, init);
const res2 = returnType === 'json' ? await res.json() : await res.text();
return res2;
} catch(e) {
console.log(e);
return returnType === 'json' ? {code:e.code||1, msg: e.message||"", data: null} : "";
}
}
})()